package com.onairm.baselibrary.mvp.base;

/**
 * Created by bqy on 2018/3/27.
 *
 * 代理模式-第二重代理-代理对象-绑定和解绑
 * 两个特点
 * 特点一：实现目标接口（可有可无）
 * 特点二：持有目标对象引用（必需）
 */

public class ProxyMvpCallback<V extends MvpView, P extends MvpPresenter<V>> implements MvpCallback<V, P> {

    private MvpCallback<V, P> mvpCallback;

    public ProxyMvpCallback(MvpCallback<V, P> mvpCallback) {
        this.mvpCallback = mvpCallback;
    }

    @Override
    public P createPresenter() {
        P presenter = mvpCallback.getPresenter();
        if (presenter == null) {
            presenter = mvpCallback.createPresenter();
        }
        if (presenter == null) {
            throw new NullPointerException("P层不能为空");
        }
        mvpCallback.setPresenter(presenter);
        return presenter;
    }

    @Override
    public P getPresenter() {
        return mvpCallback.getPresenter();
    }

    @Override
    public void setPresenter(P presenter) {
        mvpCallback.setPresenter(presenter);
    }

    @Override
    public V getMvpView() {
        return mvpCallback.getMvpView();
    }

    public void attachView() {
        getPresenter().attachView(getMvpView());
    }

    public void detachView() {
        getPresenter().detachView();
    }
}
